package com.guguju.ssms.feature.HealthMonitor;

import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.utils.AppUtils;
import com.google.gson.JsonObject;
import com.guguju.ssms.Guguju;
import com.guguju.ssms.R;
import com.guguju.ssms.constant.IntentParms;
import com.guguju.ssms.core.base.BaseFragment;
import com.guguju.ssms.core.log.LogUtil;
import com.guguju.ssms.feature.Home.HomeActivity;
import com.guguju.ssms.feature.Html.HtmlActivity;
import com.guguju.ssms.feature.login.LoginActivity;

/**
 * Created by dell on 2022-5-22.
 */
public class HealthMonitorFragment extends BaseFragment {


    /**
     * TAG fragment name.
     */
    public static final String TAG = HealthMonitorFragment.class.getName();
    RelativeLayout mTitleLayout;
    WebView webView;
    ProgressBar mProgress;
    TextView mTvTitle;
    Button mBack;

    private static final String JS_OBJECT_NAME = "GugujuApp";

    /**
     * 默认URL
     */
    private String mDefaultUrl;

    /**
     * 传入的URL
     */
    private String baseUrl;

    /**
     * 调用当前fagment的类型  0 首页调用 1 其他页面调用(Html5Activity)
     */
    private int openType;
    private String htmlFrom;



    private boolean isNewTitleBar;

    /**
     * @return classroomFragment
     */
    public static HealthMonitorFragment newInstance(String baseUrl, int openType, String htmlFrom) {
        LogUtil.i(TAG + "   create");
        Bundle args = new Bundle();
        HealthMonitorFragment fragment = new HealthMonitorFragment();
        args.putString(IntentParms.HTML5_URL, baseUrl);
        args.putString(IntentParms.HTML5_URL_FROM, htmlFrom);
        args.putInt("openType", openType);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_healthmonitor;
    }

    @Override
    protected void afterCreate() {

        webView=getView().findViewById(R.id.wv_html5);
        mProgress=getView().findViewById(R.id.pb_html5);
        mTvTitle=getView().findViewById(R.id.tv_title);
        mBack=getView().findViewById(R.id.bt_back);
        mTitleLayout=getView().findViewById(R.id.title_layout);

        if (getArguments() != null) {
            baseUrl = getArguments().getString(IntentParms.HTML5_URL);
            htmlFrom = getArguments().getString(IntentParms.HTML5_URL_FROM);
            openType = getArguments().getInt("openType");
        }
        initView();
        // 设置webView
        initWebViewSettings();
        // 加载页面
        loadWebView();

        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });

    }

    /**
     * 初始化
     */
    private void initView() {
        if (openType == 0) {
            mBack.setVisibility(View.GONE);
        } else {
            mBack.setVisibility(View.VISIBLE);
        }
    }



    /**
     * webview初始设置
     */
    private void initWebViewSettings() {
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setUseWideViewPort(true);// 双击变大，再双击后变小，当手动放大后，双击可以恢复到原始大小
        settings.setAppCacheEnabled(false);
        settings.setDomStorageEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        webView.addJavascriptInterface(new GugujuApp(), JS_OBJECT_NAME);
        webView.setWebChromeClient(new Html5WebChromeCLient());
        webView.setWebViewClient(new Html5WebViewClient());
    }

    /**
     * 加载页面
     */
    private void loadWebView() {
        LogUtil.d(TAG + "->baseUrl->" + baseUrl);
        if (!TextUtils.isEmpty(baseUrl)) {
            baseUrl = baseUrl.trim();
            loadHtmlPage(baseUrl);
        } else {
            if (openType != 0) {
                getActivity().finish();
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();
    }


    /**
     * 加载html5请求接口
     *
     * @param htmlUrl
     */
    public void loadHtmlPage(String htmlUrl) {
        String url =htmlUrl;
        if(htmlUrl.contains("appweb.guguju.com")) {
            url = getUrlParams(htmlUrl);
        }
        webView.loadUrl(url);
    }

    /**
     * 拼接网址的参数
     */
    private String getUrlParams(String baseUrl) {
        JsonObject jo = new JsonObject();

        jo.addProperty("AppType", 3);
        jo.addProperty("AppUserId", Guguju.USERID);
        jo.addProperty("AppAuth", Guguju.AUTH);
        jo.addProperty("AppVersion", AppUtils.getAppVersionName(getActivity()));
        //jo.addProperty("ChannelCode", Guguju.setupChannel);
        StringBuilder sb = new StringBuilder();
        sb.append(baseUrl);
        if (baseUrl.contains("?")) {
            sb.append("&param=");
        } else {
            sb.append("?param=");
        }
        sb.append(jo.toString());
        return sb.toString();
    }

    @Override
    public void onStop() {
        super.onStop();
    }


    final class GugujuApp {

        /**
         * 客户端H5唤起客户端弹窗提示
         *
         * @param text 客户端弹窗提示内容(string)
         */
        @JavascriptInterface
        public void AndroidAppShowAlert(String text) {
            Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();
        }

        /**
         * 客户端H5客户端跳转新开界面加载HTML h5页面
         *
         * @param url 新页面URL
         */
        @JavascriptInterface
        public void AndroidAppLoadUrlByNewWindow(String url) {
            Intent intent = new Intent(getActivity(), HtmlActivity.class);
            intent.putExtra(IntentParms.HTML5_URL, url);
            startActivity(intent);
        }

        /**
         * 客户端H5客户端关闭当前窗口回到上一个窗口
         */
        @JavascriptInterface
        public void AndroidAppGoBack() {
            if (openType != 0) {
                getActivity().finish();
            }
        }

        /**
         * 客户端H5关闭窗口打开新窗口加载html5页面
         *
         * @param url 新页面URL
         */
        @JavascriptInterface
        public void AndroidAppCloseAndOpenNewWindowLoadUrl(String url) {
            Intent intent = new Intent(getActivity(), HtmlActivity.class);
            intent.putExtra(IntentParms.HTML5_URL, url);
            startActivity(intent);
            if (openType != 0) {
                getActivity().finish();
            }
        }

        /**
         * 客户端H5唤起客户端登陆并回到指定H5页面（AppJumpLogin ）
         *
         * @param url 指定页面URL
         */
        @JavascriptInterface
        public void AndroidAppJumpLogin(String url) {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            intent.putExtra(IntentParms.LOGIN_FROM, IntentParms.LOGIN_FROM_HTML);
            startActivity(intent);
        }


        @JavascriptInterface
        public void AndroidAppLoadUrlByNewWindowNewNavStyle(String url) {
            Intent intent = new Intent(getActivity(), HtmlActivity.class);
            intent.putExtra(IntentParms.HTML5_URL, url);
            startActivity(intent);
        }

        @JavascriptInterface
        public void AndroidAwakenMoblieCall(String phoneNum) {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            Uri data = Uri.parse("tel:" + phoneNum);
            intent.setData(data);
            startActivity(intent);
        }

    }

    class Html5WebChromeCLient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            mProgress.setProgress(newProgress);
            if (newProgress == 100) {
                mProgress.setVisibility(View.GONE);
            }
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            mTvTitle.setText(title);
        }
    }

    class Html5WebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            mProgress.setVisibility(View.VISIBLE);
            view.loadUrl(url);// 使用自己的WebView组件来响应Url加载事件，而不是使用默认浏览器器加载页面
            return true;// 消耗掉这个事件。Android中返回True的即到此为止吧,事件就会不会冒泡传递了，我们称之为消耗掉
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }
    }


}
